<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="keyWord" placeholder="请输入关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="getQuery">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
    <!--
        @selection-change="selsChange"
    -->
		<el-table :data="depts" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
      <!-- 复选框 -->
			<el-table-column type="selection" width="55"></el-table-column>
      <!-- 索引 -->
			<el-table-column type="index" width="60"></el-table-column>
			<el-table-column prop="sn" label="部门编号" width="100" sortable>
			</el-table-column>
      <el-table-column prop="name" label="部门名称" width="180" sortable>
      </el-table-column>
			<el-table-column prop="state" label="状态" width="120" sortable>
        <!-- scope 当前数据 row 当前行的数据-->
        <template scope="scope">
          <div>
            <span v-if="scope.row.state=='-1'" style="color: red">停用</span>
            <span v-if="scope.row.state=='0'" style="color: green">启用</span>
          </div>
        </template>
			</el-table-column>
			<el-table-column prop="manager.username" label="管理员" width="180" sortable>
			</el-table-column>
			<el-table-column prop="parent.name" label="上级部门" width="180" sortable>
			</el-table-column>
			<el-table-column label="操作" >
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="pageSize" :total="total" :current-page="currentPage" style="float:right;">
			</el-pagination>
		</el-col>

		<!--编辑界面
		    :visible.sync用来控制弹框
		    :rules="editFormRules"  定义验证规则
		    ref="editForm"  校验的名字
		-->
		<el-dialog :title="title" :visible.sync="editFormVisible" :close-on-click-modal="false">
			<el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
				<el-form-item label="部门名称" prop="name">
					<el-input v-model="editForm.name" auto-complete="off"></el-input>
				</el-form-item>
        <el-form-item label="部门编号" prop="sn">
          <el-input v-model="editForm.sn" auto-complete="off"></el-input>
        </el-form-item>
				<el-form-item label="状态">
					<el-radio-group v-model="editForm.state">
						<el-radio class="radio" :label="0">启用</el-radio>
						<el-radio class="radio" :label="-1">禁用</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="管理员">
          <el-select v-model="editForm.manager" value-key="id" clearable placeholder="请选择">
            <!--
                :key="item.value"  表示唯一
                :label="item.label"  选中之后显示在框里面的值
                :value="item.value"  选中之后要返回给模型的值  如果这里返回的是对象那么value-key="id"必加

             -->
            <el-option v-for="item in employees" :key="item.id" :label="item.username" :value="item">
              <span style="float: left">{{ item.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>
            </el-option>
          </el-select>
				</el-form-item>
        <el-form-item label="上级部门">
          <el-cascader v-model="editForm.parent"
              :options="tree"
              :props="{ checkStrictly: true,
                        value : 'id',
                        label : 'name'
                      }"
              clearable></el-cascader>
        </el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="editFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
			</div>
		</el-dialog>

	</section>
</template>

<script>
	import util from '../../common/js/util'
	//import NProgress from 'nprogress'
	import { getUserListPage, removeUser, batchRemoveUser, editUser, addUser } from '../../api/api';

	export default {
		data() {
			return {
				filters: {
					name: ''
				},
        keyWord:"",
        title:"",
        depts: [],
        employees:[],
        tree:[],
				total: 0,
				currentPage: 1,
        pageSize:10,
				listLoading: false,
        count:0,
				sels: [],//列表选中列

				editFormVisible: false,//编辑界面是否显示
				editLoading: false,
				editFormRules: {
					name: [
					    // 必填           没有填的提示信息        失去焦点触发验证规则
						{ required: true, message: '请输入姓名', trigger: 'blur' },
            /*{ min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }*/
					]
				},
				//编辑界面数据
				editForm: {
					id: null,
					sn: '',
					name: '',
					state: -1,
          manager: null,
          parent: null
				},
			}
		},
		methods: {
			//状态显示转换
      // formatState: function (row, column) {
			// 	return row.state == 0 ? '<span>启用</span>' : row.state == -1 ? '禁用' : '未知';
			// },
      //修改currentPage
			handleCurrentChange(val) {
				this.currentPage = val;

				this.getDepts();
			},
      getQuery(){//提供一个方法出来单独做查询
        this.currentPage  = 1
        this.getDepts()
      },
			//获取部门列表
			getDepts() {
			  console.log(this.currentPage)
			  //构造参数
				let para = {
          currentPage: this.currentPage,
					pageSize: this.pageSize,
          keyWord: this.keyWord
				};
				this.listLoading = true;//忙等
        console.log(para)
        this.$http.post("/dept",para)
            .then(result=>{
                this.listLoading = false;//关闭忙等
                this.depts = result.data.pageList
                this.total = result.data.total

            }).catch(result=>{
                this.listLoading = false;//关闭忙等
            });
			},
      getEmployee(){
        this.$http.get("/emp")
            .then(result=>{
              this.employees = result.data
            }).catch(result=>{
        })
      },
      getTree(){
        this.$http.get("/dept")
            .then(result=>{
              this.tree = result.data
              console.log(this.tree)
            }).catch(result=>{
        })
      },
			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '温馨提示', {
					type: 'warning'
				}).then(() => { //点击确认按钮
					this.listLoading = true;//开启列表的忙等

          this.$http.delete("/dept/"+row.id)
              .then(result=>{
                  console.log(result)
                  if(result.data.state){
                    this.$message({
                      message: result.data.message,
                      type: 'success'
                    });
                  }else{
                    this.$message({
                      message: result.data.message,
                      type: 'error'
                    });
                  }
                this.listLoading = false;
                // this.currentPage = 1
                this.getDepts()

              }).catch(result=>{
                this.listLoading = false;
              })

					//NProgress.start();
					/*removeUser(para).then((res) => {
						this.listLoading = false;
						//NProgress.done();
						this.$message({
							message: '删除成功',
							type: 'success'
						});
						this.getDepts();
					});*/
				}).catch(() => {//点击取消按钮

				});
			},
			//显示编辑界面
			handleEdit: function (index, row) {
        this.getEmployee()
        this.getTree()
        this.title = "编辑"
				this.editFormVisible = true;//打开模态框
        //克隆 复制Object.assign({}, row);
				this.editForm = Object.assign({}, row);
        // console.log(this.editForm.dirPath.split("/"))//  ""  "334417" "334418" "334419"
        let ids =  this.editForm.dirPath.split("/")
        var path = []
        for (let i = 1; i <ids.length-1; i++) {
            //我们回显的时候一定是整型    parseInt 将字符串转为 int
            path.push(parseInt(ids[i]))
        }
        this.editForm.parent = path
 			},
			//显示新增界面
			handleAdd: function () {
			  this.getEmployee()
        this.getTree()
			  this.title = "新增"
				this.editFormVisible = true;
			  //清空模态框
				this.editForm={
          id: null,
          sn: '',
          name: '',
          state: -1,
          manager: null,
          parent: null
        };
			},
			//编辑
			editSubmit: function () {
			  //this.$refs获取当前所有的ref="editForm"   validate 触发验证规则
				this.$refs.editForm.validate((valid) => {
				  //valid 验证的结果
					if (valid) {
						this.$confirm('确认提交吗？', '蔡飞飞的提示', {}).then(() => {
							this.editLoading = true;//开启按钮
							//NProgress.start();
							let para = Object.assign({}, this.editForm);
              if(para.parent){//有值
                //将数组转为对象             //获取最后一个id
                para.parent = {"id":para.parent[para.parent.length - 1]}
              }

              this.$http.put("/dept",para).then(result=>{
                console.log(result)
                if(result.data.state){
                  this.$message({
                    message: result.data.message,
                    type: 'success'
                  });
                  //只有成功了才关闭模态框
                  this.editFormVisible = false
                }else{
                  this.$message({
                    message: result.data.message,
                    type: 'error'
                  });
                }
                this.editLoading = false;
                this.currentPage = 1
                this.getDepts()

              }).catch(result=>{
                this.editLoading = false;
              })

							//para.birth = (!para.birth || para.birth == '') ? '' : util.formatDate.format(new Date(para.birth), 'yyyy-MM-dd');
							/*editUser(para).then((res) => {
								this.editLoading = false;
								//NProgress.done();
								this.$message({
									message: '提交成功',
									type: 'success'
								});
								this.$refs['editForm'].resetFields();
								this.editFormVisible = false;
								this.getDepts();
							});*/
						});
					}
				});
			},
			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
        //获取选中的id
				var ids = this.sels.map(item => item.id);
				this.$confirm('确认删除选中记录吗？', '温馨提示', {
					type: 'warning'
				}).then(() => {//确定
					this.listLoading = true;//打开忙等

          this.$http.patch("/dept",ids).then(result=>{
            this.listLoading = false;//打开忙等
            if(result.data.state){
              this.$message({
                message: result.data.message,
                type: 'success'
              });
              //this.currentPage = 1 //跳转首页
              this.getDepts();  //获取数据
            }else {
              this.$message({
                message: result.data.message,
                type: 'error'
              });
            }
          }).catch(result=>{
            this.listLoading = false;//打开忙等
          })
					//NProgress.start();
					//let para = { ids: ids };
					// batchRemoveUser(para).then((res) => {
					// 	this.listLoading = false;
					// 	//NProgress.done();
					// 	this.$message({
					// 		message: '删除成功',
					// 		type: 'success'
					// 	});
					// 	this.getDepts();
					// });
				}).catch(() => {

				});
			}
		},
		mounted() {
			this.getDepts();
		}
	}

</script>

<style scoped>

</style>